// ==UserScript==
// @name         文件蜈蚣获取当天激活码
// @version      0.0.10
// @description  文件蜈蚣获取当天激活码
// @author       cy2
// @match        http://filecxx.com/zh_CN/activation_code.html
// @match        https://filecxx.com/zh_CN/activation_code.html
// @homepage     https://gitee.com/caiyaoyuan/script-sets/tree/master
// @namespace    https://gitee.com/caiyaoyuan/script-sets/blob/master/JavaScript/FilecxxActivationCode.js
// @updateURL    https://gitee.com/caiyaoyuan/script-sets/raw/master/JavaScript/FilecxxActivationCode.js
// @downloadURL  https://gitee.com/caiyaoyuan/script-sets/raw/master/JavaScript/FilecxxActivationCode.js
// @icon         https://filecxx.com/favicon.ico
// @run-at       document-end
// @grant        unsafeWindow
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @grant        GM_info
// ==/UserScript==

(function() {
    'use strict';

    var window = unsafeWindow || window;

    const itemMatchRegexp = new RegExp("\\d{4}-\\d{2}-\\d{2}\\s*00:00:00\\s*-\\s*\\d{4}-\\d{2}-\\d{2}\\s*00:00:00\\n[0-9a-zA-Z_-]{173}", "g");

    Date.prototype.format = function(fmt = "yyyy-MM-dd HH:mm:ss:S") {
        let opt = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours()%12, 				  //小时   12小时制
            "H+" : this.getHours(),                   //小时   24小时制
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(let k in opt){
            if(new RegExp("("+ k +")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (opt[k]) : (("00"+ opt[k]).substr((""+ opt[k]).length)));
            }
        }
        return fmt;
    }

    Date.prototype.isDuringDate = function(beginDateStr, endDateStr) {
        let beginDate = new Date(beginDateStr),
            endDate = new Date(endDateStr);
        if (this >= beginDate && this <= endDate) {
            return true;
        }
        return false;
    }

    function checkMsg(conf) {
        if(!conf && conf.err){
            throw new Error(conf?.msg || "脚本运行错误");
        }
    }

	function formater(conf){
	    let html = `<div id="copy-info">
        <style>
        .succes{color: #00db00;}.error{color: #ff1717;}#copy-info{}
	    #copy-info>div>span{ font-size: 1.1rem;padding: 0.5rem; }
        #copy-info>div>span:not(:first-child):before { content: "|";  margin-left: -0.5rem;  margin-right: 0.5rem; }
	    #copy-info>div>span.copy-btn{ cursor: pointer; user-select: none; }
	    #copy-info>div>span.copy-btn:hover{ color: #ff0000; }
        #copy-info>div>span.copy-btn:hover:before { color: #393d3f; }
        #copy-info>div.cur-code{ word-break: break-all; padding: 0.5rem; border: 1px solid #999999; border-radius: 0.5rem; }
        </style>
        <div>
        <span class="date-range-start" title="激活码有效开始时间">${conf.dates[0]}</span>
        <span class="date-range-end" title="激活码有效结束时间">${conf.dates[1]}</span>
        <span class="cur-date" title="当前日期">${conf.format}</span>
	    <span class="copy-btn" data-date="${conf.format}" data-code="${conf.codes}" title="点击复制激活码">复制</span>
	    </div>
		<div class="cur-code ${conf.class}">${conf.codes}</div>
		</div>`;
		return html;
	}

    function addCss(conf){
        let css = `.succes{color: #00db00;}.error{color: #ff1717;}#copy-info{}
	    #copy-info>div>span{ font-size: 1.1rem;padding: 0.5rem; }
	    #copy-info>div>span.copy-btn{ cursor: pointer; user-select: none; }
	    #copy-info>div>span.copy-btn:hover{ color: #ff0000; }
        #copy-info>div.cur-code{ word-break: break-all; padding: 0.5rem; border: 1px solid #999999; border-radius: 0.5rem; }`;
        conf.css = css;
        GM_addStyle(css);
        checkMsg(conf);
    }

    function getData(conf) {
        let flag = false;
        let txt = window.document.querySelector("#code_list>#codes").innerHTML;
        let datas = txt.match(itemMatchRegexp);
		for(let items of datas) {
			if(items.trim().length == 0){
				continue;
			}
			let array = items.split("\n");
			let dates = array[0].split(" - ");
			let codes = array[1];
			if(conf.curDate.isDuringDate(dates[0], dates[1])){
                flag = true;
                conf.class = "succes";
                conf.dates = dates;
                conf.codes = codes;
                console.info(conf.format, dates, codes);
				break;
			}
		}
        if(!flag){
            conf.err = true;
            conf.msg = "未获取到当天激活码";
        }
        checkMsg(conf);
    }

	function addHtml(conf){
        let html = formater(conf);
        conf.html = html;
        let $title = window.document.querySelector("body .body>.section:first-child>h1");
		$title.insertAdjacentHTML("afterend", html);// beforebegin afterbegin beforeend afterend
        checkMsg(conf);
    }

    function addEvent(conf){
        let $copyBtn = window.document.querySelector("body #copy-info .copy-btn");
        $copyBtn.addEventListener("click", (e)=> {
            clearTimeout(conf.pid);
            ++conf.count;
            console.info("count: " + conf.count, "pid: " + conf.pid);
            conf.pid = setTimeout(() => {
                conf.count = 0;
                console.info("count: " + conf.count, "pid: " + conf.pid);
                GM_setClipboard(conf.codes);
                $copyBtn.innerText = '复制成功';
                $copyBtn.classList.add('succes');
                setTimeout(() => {
                    $copyBtn.innerText = '复制';
                    $copyBtn.classList.remove('succes');
                }, 3000);
            }, 500);
        });
        checkMsg(conf);
    }

    function run(){
        console.info("script version:" + GM_info.script.version);
        let curDate = new Date(), format = curDate.format('yyyy-MM-dd');
        let conf = { pid:0, count: 0, curDate: curDate, format: format, class: "error", codes: "未获取到当天激活码" };
        //addCss(conf);
        getData(conf);
        addHtml(conf);
        addEvent(conf);
    }

    run();
})();